package cn.itcast.take_delivery.web.action;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;

import cn.itcast.bos.domain.take_delivery.WayBill;
import cn.itcast.bos.util.FileUtils;
import cn.itcast.bos.web.action.BaseAction;
import cn.itcast.take_delivery.service.WayBillService;

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class WayBillAction extends BaseAction<WayBill> {

	private static final Logger logger = Logger.getLogger(WayBillAction.class);
	@Autowired
	private WayBillService wayBillService;

	// 添加
	@Action(value = "waybill_save", results = { @Result(name = "success", type = "json") })
	public String save() {
		Map<String, Object> result = new HashMap<String, Object>();
		try {

			// 去除 没有id的order对象
			if (model.getOrder() != null && 
					(model.getOrder().getId() == null || model.getOrder().getId() == 0)) {
						model.setOrder(null);
			}

			wayBillService.save(model);
			result.put("success", true);
			result.put("msg", "添加成功");
			logger.info("添加成功,运单号: " + model.getWayBillNum());
		} catch (Exception e) {
			result.put("success", false);
			result.put("msg", "添加失败");
			logger.error("添加失败,运单号为: " + model.getWayBillNum(), e);
		}
		ServletActionContext.getContext().getValueStack().push(result);
		return SUCCESS;
	}

	// 分页
	@Action(value = "waybillpage", results = { @Result(name = "success", type = "json") })
	public String wayBillPage() {
		Pageable pageable = new PageRequest(page - 1, rows, new Sort(new Sort.Order(Sort.Direction.DESC, "id")));
		Page<WayBill> pagedata = wayBillService.findByPage(model,pageable);
		pushToValueStack(pagedata);
		return SUCCESS;
	}

	@Action(value = "findByWayBullNum", results = {
			@Result(name = "success", type = "json", params = { "excludeNullProperties", "true" }) })
	public String findByWayBillNum() {
		Map<String, Object> map = new HashMap<String, Object>();
		WayBill wayBill = wayBillService.findByWayBillNum(model.getWayBillNum());
		if (wayBill == null) {
			map.put("success", false);
		} else {
			map.put("success", true);
			map.put("wayBillData", wayBill);
		}
		ActionContext.getContext().getValueStack().push(map);
		return SUCCESS;
	}
	
	//导出报表
	@Action(value="report_exportXls")
	public String exportXls() throws Exception{
		List<WayBill> wayBills = wayBillService.findWayBill(model);
		
		//生成文件
		HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
		//创建sheet表
		HSSFSheet sheet = hssfWorkbook.createSheet("运单数据表");
		//表头
		HSSFRow headRow = sheet.createRow(0);
		headRow.createCell(0).setCellValue("运单号");
		headRow.createCell(1).setCellValue("寄件人");
		headRow.createCell(2).setCellValue("寄件人电话");
		headRow.createCell(3).setCellValue("寄件人地址");
		headRow.createCell(4).setCellValue("收件人");
		headRow.createCell(5).setCellValue("收件人电话");
		headRow.createCell(6).setCellValue("收件人地址");
		//数据
		for (WayBill wayBill : wayBills) {
			HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum()+1);
			dataRow.createCell(0).setCellValue(wayBill.getWayBillNum());
			dataRow.createCell(1).setCellValue(wayBill.getSendName());
			dataRow.createCell(2).setCellValue(wayBill.getSendMobile());
			dataRow.createCell(3).setCellValue(wayBill.getSendAddress());
			dataRow.createCell(4).setCellValue(wayBill.getRecName());
			dataRow.createCell(5).setCellValue(wayBill.getRecMobile());
			dataRow.createCell(6).setCellValue(wayBill.getRecAddress());
		}
		// 下载导出
		// 设置头信息
		ServletActionContext.getResponse().setContentType(
				"application/vnd.ms-excel");
		String filename = "运单数据.xls";
		String agent = ServletActionContext.getRequest()
				.getHeader("user-agent");
		filename = FileUtils.encodeDownloadFilename(filename, agent);
		ServletActionContext.getResponse().setHeader("Content-Disposition",
				"attachment;filename=" + filename);

		ServletOutputStream outputStream = ServletActionContext.getResponse()
				.getOutputStream();
		hssfWorkbook.write(outputStream);

		// 关闭
		hssfWorkbook.close();

		return NONE;
	}

}
